# coding: utf-8

from celery import shared_task
from services.datamodel.share import stats_logger
from django.core.cache import cache
import json
from services.datamodel.live.models import (mm_Live, mm_LiveTally, mm_LiveGroup, mm_LiveData, mm_LivePeopleFlow, mm_LiveImUser)
from services.datamodel.student.models import mm_Student
import logging
app_logger = logging.getLogger("student")
from lib.live.LiveMain import LiveServers
import time, random
import datetime
import traceback
from django.db.models import F, Sum
from django.db import transaction


# 直播人流量回调
@shared_task(ignore_result=True)
def handle_peopleflow_join(group_id, users, times):
    try:
        app_logger.error("用户加入")
        # t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        # 这里先标记，其实应该取status=2的，但是不确定回调的先后
        live = mm_Live.filter(room_id=group_id).values("id").order_by("-created_at").first()
        g_obj = mm_LiveGroup.filter(live_id=live['id']).first()
        live_data, _ = mm_LiveData.get_or_create(live_id=live['id'])
        # 这里记录
        for v in users:
            s_id = int(v['Member_Account'])
            # 统计pv，uv
            channel = mm_Student.filter(pk=s_id).values('channel').first()
            mm_LiveImUser.update_or_create(student_id=s_id, group_id=g_obj.id, defaults={"channel": channel['channel']})
            live_data.pv = F('pv') + 1
            if not cache.get('live_uv:' + str(live['id']) + ':' + str(s_id)):
                live_data.uv = F('uv') + 1
                cache.set('live_uv:' + str(live['id']) + ':' + str(s_id), 1, 3600 * 24)
            if not cache.get('live_pv_' + str(live['id'])):
                cache.set('live_pv_' + str(live['id']), 0, 3600 * 24 * 30)
            cache.incr('live_pv_' + str(live['id']), 1)
            cache.set('live_uv:' + str(live['id']) + ':' + str(s_id), 1, 3600 * 24)
            # 记录进入时间
            if not mm_LivePeopleFlow.filter(live_id=live['id'], student_id=s_id, status=0).exists():
                mm_LivePeopleFlow.create(live_id=live['id'], student_id=s_id, join_time=int(times/1000))
        live_data.save()
        return True
    except:
        err = traceback.format_exc()
        app_logger.error(err)
        return False


@shared_task(ignore_result=True)
def handle_peopleflow_exit(group_id, users, times):
    try:
        app_logger.error("用户退出")
        # 这里先标记，其实应该取status=2的，但是不确定回调的先后
        live = mm_Live.filter(room_id=group_id).values("id").order_by("-created_at").first()
        stus = mm_LivePeopleFlow.filter(status=0, live_id=live['id'], student_id__in=[v['Member_Account'] for v in users])
        if stus:
            for s in stus:
                mm_LiveImUser.filter(group__live_id=live['id'], student_id=s.student_id).update(
                    watch_time=F('watch_time') + int(times / 1000) - s.join_time
                )
            stus.update(status=1, exit_time=int(times / 1000))
        return True
    except:
        err = traceback.format_exc()
        app_logger.error(err)
        return False